package com.qlogic.commons.utils.json;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import com.qlogic.commons.utils.Null;

public class JsonObject implements JsonEntity {

	private static final long serialVersionUID = -374323560863553121L;

	public static final Null	NULL 			= new Null();
	
	public static final String 	 	NULL_VALUE 		= "null";
	public static final String 	 	FALSE 			= "false";
	public static final String 	 	TRUE 			= "true";
	public static final String 	 	EMPTY_OBJECT 	= "{}";
	
	public static final String OBJECT_OPEN 	= "{";
	public static final String OBJECT_CLOSE = "}";
	public static final String ARRAY_OPEN 	= "[";
	public static final String ARRAY_CLOSE 	= "]";
	
	public static final String PRINT_AS_ARRAY = "PrintAsArray";
	
	private Map<String, Object> values;

	public JsonObject() {
	}
	
	public JsonObject (String json) throws JsonException {
		this (new JsonParser (json));
	}

	public JsonObject(JsonParser jt) throws JsonException {
		char c;
		String key;

		if (jt.nextClean() != '{') {
			throw jt.syntaxError("A JSONObject text must begin with '{'");
		}
		for (;;) {
			c = jt.nextClean();
			switch (c) {
			case 0:
				throw jt.syntaxError("A JSONObject text must end with '}'");
			case '}':
				return;
			default:
				jt.back();
				key = jt.nextValue().toString();
			}

			c = jt.nextClean();
			if (c == '=') {
				if (jt.next() != '>') {
					jt.back();
				}
			} else if (c != ':') {
				throw jt.syntaxError("Expected a ':' after a key");
			}
			set (key, jt.nextValue());

			switch (jt.nextClean()) {
			case ';':
			case ',':
				if (jt.nextClean() == '}') {
					return;
				}
				jt.back();
				break;
			case '}':
				return;
			default:
				throw jt.syntaxError("Expected a ',' or '}'");
			}
		}
	}

	public void set (String name, Object value) {
		if (name == null || value == null) {
			return;
		}
		if (values == null) {
			values = new LinkedHashMap<String, Object>();
		}
		values.put(name, value);
	}

	public void remove (String name) {
		if (name == null || values == null) {
			return;
		}
		values.remove(name);
	}

	public Object get (String name) {
		if (name == null || values == null) {
			return null;
		}
		return values.get (name);
	}

	public Iterator<String> keys () {
		if (values == null) {
			return null;
		}
		return values.keySet().iterator();
	}

	public Iterator<Object> values () {
		if (values == null) {
			return null;
		}
		return values.values().iterator();
	}

	public boolean isEmpty () {
		return values == null || values.isEmpty();
	}

	public int count () {
		return values == null ? 0 : values.size();
	}

	public void clear () {
		if (values == null) {
			return;
		}
		Iterator<Object> valuesIter = values();
		while (valuesIter.hasNext()) {
			Object value = valuesIter.next();
			if (value instanceof JsonObject) {
				((JsonObject) value).clear();
			} else if (value instanceof JsonArray) {
				((JsonArray) value).clear();
			}
		}
		values.clear();
		values = null;
	}

    public String getString (String name) {
    	Object value = get (name);
    	if (value == null) {
    		return null;
    	}
        return value.toString ();
    }

    public boolean getBoolean (String name) {
        Object value = get (name);
        if (Boolean.FALSE.equals(value) ||
                (value instanceof String &&
                ((String)value).equalsIgnoreCase (FALSE))) {
            return false;
        } else if (Boolean.TRUE.equals (value) ||
                (value instanceof String &&
                ((String)value).equalsIgnoreCase(TRUE))) {
            return true;
        }
        return false;
    }
	
    public double getDouble (String name) throws JsonException {
    	Object value = get (name);
    	if (value == null) {
    		throw new JsonException (quote (name) + " is null");
    	}
        try {
        	return value instanceof Number ?
                    ((Number)value).doubleValue() :
                    Double.valueOf((String)value).doubleValue();
        } catch (Throwable th) {
            throw new JsonException (th, "Value Of [" + quote (name) +
                "] is not a number.");
        }
    }

    public int getInt (String name) throws JsonException {
        Object value = get (name);
        if (value == null) {
    		throw new JsonException (quote (name) + " is null");
    	}
        return value instanceof Number ?
                ((Number)value).intValue() : (int)getDouble(name);
    }

    public long getLong (String name) throws JsonException {
        Object value = get (name);
        if (value == null) {
    		throw new JsonException (quote (name) + " is null");
    	}
        return value instanceof Number ?
                ((Number)value).longValue() : (long)getDouble (name);
    }

    public JsonArray getArray (String name) throws JsonException {
        Object value = get (name);
        if (value == null) {
        	return null;
    	}
        if (value instanceof JsonArray) {
            return (JsonArray)value;
        }
        throw new JsonException("Value Of [" + quote (name) +
                "] is not a JsonArray.");
    }

    public JsonObject getObject (String name) throws JsonException {
        Object value = get (name);
        if (value == null) {
        	return null;
    	}
        if (value instanceof JsonObject) {
            return (JsonObject)value;
        }
        throw new JsonException("Value Of [" + quote (name) +
                "] is not a JsonObject.");
    }

    public boolean isNull (String name) {
    	Object value = get (name);
        return value == null || NULL.equals (value);
	}

	public String toString () {
		try {
			return toString (0);
		} catch (Exception e) {
			return null;
		}
	}

	public String toString (int indentFactor) throws JsonException {
		return toString (indentFactor, 0);
	}

	private String toString (int indentFactor, int indent) throws JsonException {
		if (NULL.equals (this)) {
			return NULL_VALUE;
		}
		if (isEmpty()) {
			return EMPTY_OBJECT;
		}
		Iterator<String> keys = keys();
		boolean asArr = getBoolean (PRINT_AS_ARRAY);
		StringBuilder sb = new StringBuilder (asArr ? "[" : "{");
		int newindent = indent + indentFactor;
		String key;
		if (count() == 1) {
			key = keys.next();
			if (!asArr) {
				sb.append(quote(key));
				sb.append(':');
			}
			if (indentFactor > 0) {
				sb.append(" ");
			}
			sb.append (valueToString (get(key), indentFactor, indent));
		} else {
			while (keys.hasNext()) {
				key = keys.next();
				if (PRINT_AS_ARRAY.equals (key)) {
					continue;
				}
				if (sb.length() > 1) {
					sb.append(",");
				} 
				if (indentFactor > 0) {
					sb.append('\n');
					for (int j = 0; j < newindent; j += 1) {
						sb.append(' ');
					}
				}
				if (!asArr) {
					sb.append(quote(key));
					sb.append(':');
				}
				if (indentFactor > 0) {
					sb.append(" ");
				}
				sb.append(valueToString(get(key), indentFactor, newindent));
			}
			if (sb.length() > 1) {
				if (indentFactor > 0) {
					sb.append('\n');
					for (int j = 0; j < indent; j += 1) {
						sb.append(' ');
					}
				}
			}
		}
		if (asArr) {
			sb.append(']');
		} else {
			sb.append('}');
		}
        String s = sb.toString();
        sb.setLength (0);
        sb = null;
        return s;
	}

	public static String quote (String string) {
		if (string == null || string.length() == 0) {
			return "\"\"";
		}
		char b;
		char c = 0;
		int i;
		int len = string.length();
		StringBuilder sb = new StringBuilder(len + 4);
		String t;

		sb.append('"');
		for (i = 0; i < len; i += 1) {
			b = c;
			c = string.charAt(i);
			switch (c) {
			case '\\':
			case '"':
				sb.append('\\');
				sb.append(c);
				break;
			case '/':
				if (b == '<') {
					sb.append('\\');
				}
				sb.append(c);
				break;
			case '\b':
				sb.append("\\b");
				break;
			case '\t':
				sb.append("\\t");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\r':
				sb.append("\\r");
				break;
			default:
				if (c < ' ' || (c >= '\u0080' && c < '\u00a0')
						|| (c >= '\u2000' && c < '\u2100')) {
					t = "000" + Integer.toHexString(c);
					sb.append("\\u" + t.substring(t.length() - 4));
				} else {
					sb.append(c);
				}
			}
		}
		sb.append('"');
        String s = sb.toString();
        sb.setLength (0);
        sb = null;
        return s;
	}

	static String valueToString (Object value, int indentFactor, int indent)
			throws JsonException {
		if (value == null || value.equals (null)) {
			return NULL_VALUE;
		}
		if (value instanceof Number) {
			return numberToString ((Number) value);
		}
		if (value instanceof Boolean) {
			return value.toString();
		}
		if (value instanceof JsonObject) {
			return ((JsonObject) value).toString (indentFactor, indent);
		}
		if (value instanceof JsonArray) {
			return ((JsonArray) value).toString (indentFactor, indent);
		}
		return quote (value.toString());
	}

	static String valueToString (Object value) throws JsonException {
		if (value == null || NULL.equals (value)) {
			return NULL_VALUE;
		}
		if (value instanceof Number) {
			return numberToString((Number) value);
		}
		if (value instanceof Boolean || value instanceof JsonObject
				|| value instanceof JsonArray) {
			return value.toString ();
		}
		return quote (value.toString());
	}

	static String numberToString (Number n) throws JsonException {
		if (n == null) {
			return NULL_VALUE;
		}
		
		validate (n);

		String s = n.toString();
		if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
			while (s.endsWith("0")) {
				s = s.substring(0, s.length() - 1);
			}
			if (s.endsWith(".")) {
				s = s.substring(0, s.length() - 1);
			}
		}
		return s;
	}

	static void validate(Object o) throws JsonException {
		if (o != null) {
			if (o instanceof Double) {
				if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
					throw new JsonException(
							"JSON does not allow non-finite numbers.");
				}
			} else if (o instanceof Float) {
				if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
					throw new JsonException(
							"JSON does not allow non-finite numbers.");
				}
			}
		}
	}

}